# -*- coding: utf-8 -*-
"""
查询关键  挖掘关键词  混合模式
Author:YSK
Date:2021/12/28
"""

import xlsxwriter as xw
from openpyxl import load_workbook
import os
import requests
import json
import datetime
import random
import time



PvSearchUrl = "https://api.baidu.com/json/sms/service/PvSearchFunction/getPvSearch"
KRServiceUrl = "https://api.baidu.com/json/sms/service/KRService/getKRByQuery"

http_headers = {
    "Accept-Encoding": "gzip, deflate",
    "Content-Type": "application/json",
    "Accept": "application/json"
}


def KRService_data(query, maxNum):
    user_payload = {
        "header": {
            "username": "monfarn1",
            "password": "SZzkzj1234",
            "token": "6e8d83b973f91f7f7d2b2c054fa05216",
            "action": "API-PYTHON"
        },
        "body": {
            "seedFilter": {
                "device": 0,
                "maxNum": maxNum,
                "negativeWords": [
                    "123"
                ],
                "positiveWord": query,
                "regionExtend": False,
                "removeDuplicate": False,
                "removeCampaignDuplicate": False,
                "removeBrandWords": False
            },
            "query": query
        }
    }

    return user_payload


def data_box(kerword, orderBy, order):
    user_payload = {
        "header": {
            "username": "monfarn1",
            "password": "SZzkzj1234",
            "token": "6e8d83b973f91f7f7d2b2c054fa05216",
            "action": "API-PYTHON"
        },
        "body": {
            "bidWordSource": "wordList",
            "device": 0,
            "orderBy": orderBy,
            "order": order,
            "keywordList": [
                {
                    "keywordName": kerword,
                    "matchType": 1,
                    "phraseType": 1
                }
            ]
        }
    }

    return user_payload


def kwc_to_string(num):
    kwc = {
        0: "zero",
        1: "高",
        2: "中",
        3: "低"
    }
    return kwc.get(num, None)


def compe_to_string(num):
    kwc = {
        0: "zero",
        1: "低",
        2: "中",
        3: "高"
    }
    return kwc.get(num, None)


def matchType_to_string(num):
    matchType = {
        1: "精确匹配",
        2: "短语匹配",
        3: "智能匹配"
    }
    return matchType.get(num, None)


def orderBy_to_string(num):
    orderBy = {
        1: "price",
        2: "averageMonthPv",
        3: "averageMonthPvMobile",
        4: "averageMonthPvPc",
        5: "show",
        6: "click",
        7: "pcPrice",
        8: "mobilePrice",
    }
    return orderBy.get(int(num), "price")


def order_to_string(num):
    order = {
        1: "asc",
        2: "desc"
    }
    return order.get(int(num), "desc")


"""
keywordName 	关键词字面
price           指导价
matchType       匹配模式    
phraseType      细分匹配模式
kwc             竞价激烈程度  1-高  2-中  3-低
showReasons     举荐理由（特色）
averageMonthPv  月均搜索量
averageMonthPvPc 月均计算机搜索量
averageMonthPvMobile 月均移动搜索量
show            预估月均展现
click           预估月均点击
pcPrice         关键词计算机指导价
mobilePrice     关键词移动指导价

"""


def xw_toExcel(data, fileName):  # xlsxwriter库储存数据到excel
    workbook = xw.Workbook(fileName)  # 创建工作簿
    worksheet1 = workbook.add_worksheet("sheet1")  # 创建子表
    worksheet1.activate()  # 激活表
    title = ['关键词', '指导价', '匹配模式', '竞价激烈程度', '月均搜索量', '月均计算机搜索量', '月均移动搜索量', '预估月均展现', '预估月均点击', '关键词计算机指导价',
             '关键词移动指导价']  # 设置表头
    worksheet1.write_row('A1', title)  # 从A1单元格开始写入表头
    i = 2  # 从第二行开始写入数据
    for j in range(len(data)):
        try:
            insertData = [
                data[j]['data'][0]["keywordName"],
                data[j]['data'][0]["price"],
                matchType_to_string(data[j]['data'][0]["matchType"]),
                kwc_to_string(data[j]['data'][0]["kwc"]),
                data[j]['data'][0]["averageMonthPv"],
                data[j]['data'][0]["averageMonthPvPc"],
                data[j]['data'][0]["averageMonthPvMobile"],
                data[j]['data'][0]["show"],
                data[j]['data'][0]["click"],
                data[j]['data'][0]["pcPrice"],
                data[j]['data'][0]["mobilePrice"]
            ]

            row = 'A' + str(i)
            worksheet1.write_row(row, insertData)
            i += 1
        except IndexError:
            pass
    workbook.close()  # 关闭表


"""
word            推荐词
competition     竞争激烈程度 1-低  2-中  3-高
PV              月均搜索量
pcPV            月均计算机搜索量
mobilePV        月均移动搜索量
show            预估月均展现
click           预估月均点击
competitionPc   计算机竞争激烈程度
competitionWise 移动竞争激烈程度
groupName       关键词分组名
recommendPricePc 计算机指导价
recommendPriceMobile    移动指导价
"""


def KBY_toExcel(fileName, data):
    workbook = xw.Workbook(fileName)  # 创建工作簿
    worksheet1 = workbook.add_worksheet("sheet1")  # 创建子表
    worksheet1.activate()  # 激活表
    title = ['关键词', '竞争激烈程度', '月均搜索量', '月均计算机搜索量', '月均移动搜索量', '预估月均展现', '预估月均点击', '计算机竞争激烈程度', '移动竞争激烈程度', '关键词分组名',
             '计算机指导价', '移动指导价']  # 设置表头
    worksheet1.write_row('A1', title)  # 从A1单元格开始写入表头
    i = 2  # 从第二行开始写入数据
    for j in range(len(data)):
        try:
            insertData = [
                data[j]["word"],
                compe_to_string(data[j]["competition"]),
                data[j]["pv"],
                data[j]["pcPV"],
                data[j]["mobilePV"],
                data[j]["show"],
                data[j]["click"],
                compe_to_string(data[j]["competitionPc"]),
                compe_to_string(data[j]["competitionWise"]),
                data[j]["groupName"],
                data[j]["recommendPricePc"],
                data[j]["recommendPriceMobile"]
            ]
            row = 'A' + str(i)
            worksheet1.write_row(row, insertData)
            i += 1
        except IndexError:
            pass
    workbook.close()  # 关闭表


#    挖掘关键词 启动函数


def excavate(KRServiceUrl,http_headers):
    query = (input("请输入要挖掘的关键词："))
    maxnum = (input("请输入要挖掘多少条数据（1-1000）："))

    KRuser_payload = json.dumps(KRService_data(query, maxnum))
    response = requests.request("POST", KRServiceUrl, data=KRuser_payload, headers=http_headers)
    KBYList = json.loads(response.text.encode('utf-8'))

    KRfilename = '{}-{}.xlsx'.format(query, datetime.datetime.now().strftime('%Y-%m-%d'))
    KBY_toExcel(KRfilename, KBYList['body']['data'])
    print('挖掘成功，文件名为：：{}'.format(KRfilename))
    return KRfilename


#    查询关键词 启动函数


def query_crux(PvSearchUrl, http_headers, KRfilename=None):
    orderByInput = (input(
        "请输入要以何种类型排序的序号：\n1.指导价排序 \n2.月均搜索量 \n3.月均移动搜索量 \n4.月均计算机搜索量 \n5.预估月均展现 \n6.预估月均点击 \n7.计算机指导价 \n8.预估移动指导价\n请输入序号：").split())
    orderBy = orderBy_to_string(orderByInput[0])
    orderInput = (input("请输入要以何种方式排序的序号：\n1.升序 \n2.降序\n请输入序号："))
    order = order_to_string(orderInput[0])

    ExcelList = []
    # 打开文件
    if KRfilename is None:
        keywordFile = os.getcwd() + 'checkwords.xlsx'
    else:
        keywordFile = os.getcwd() + '/{}'.format(KRfilename)

    wb = load_workbook(keywordFile)
    sheet = wb.sheetnames
    core_list = []
    for k in range(0, len(sheet)):
        ws = wb[sheet[k]]
        rows = ws.max_row
        columns = ws.max_column
        if rows - 1 == 0 and columns - 1 == 0:
            break
        else:
            for i in range(2, rows + 1):  # 从第二行开始遍历
                for j in range(1, columns + 1):
                    if j == 1:  # 只取第一列数据
                        excelStr = ws.cell(i, j).value
                        core_list.append(excelStr)

    for line in core_list:
        print('正在查询关键字：：{}'.format(line))
        user_payload = json.dumps(data_box(line, orderBy, order))
        response = requests.request("POST", PvSearchUrl, data=user_payload, headers=http_headers)
        json_res = json.loads(response.text.encode('utf-8'))
        ExcelList.append(json_res['body']['data'][0])
        print("查询成功")
        # time.sleep(2)  # 每个词的查询间隔时间为2秒，如果不怕被封，可以直接去掉

    fileName = '{}-{}.xlsx'.format(datetime.datetime.now().strftime('%Y-%m-%d'), random.randint(1000, 9999))
    xw_toExcel(ExcelList, fileName)


"""
选择模式  1.挖掘关键词  2.关键词流量 3.混合
"""
TypePattern = (input("请输入要进行的程序的序号：\n1.挖掘关键词 \n2.查询关键词流量 \n3.混合模式\n请输入序号："))
print(TypePattern)
if TypePattern == '1':
    excavate(KRServiceUrl, http_headers)
elif TypePattern == '2':
    query_crux(PvSearchUrl, http_headers)
elif TypePattern == '3':
    KRfilename = excavate(KRServiceUrl, http_headers)
    query_crux(PvSearchUrl, http_headers, KRfilename)
